package org.shzhyun.tools;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@Slf4j
public class FtpUploadUtil {

    public static void main(String[] args) {
        String server = "43.255.31.198"; // FTP 服务器地址
        int port = 21; // FTP 端口，默认是 21
        String user = "qbqb"; // FTP 用户名
        String password = "zNy2b7bKtk8FERY8"; // FTP 密码
        String localFolderPath = "/Users/gds/project2025/qb/Questions/BlanksWordsFill"; // 本地文件夹路径
        String remoteFolderPath = "/Questions/BlanksWordsFill"; // 远程文件夹路径

        FTPClient ftpClient = new FTPClient();
        try {
            // 连接到 FTP 服务器
            ftpClient.connect(server, port);
            ftpClient.login(user, password);
            ftpClient.enterLocalPassiveMode();
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

            log.info("localFolderPath:{},remoteFolderPath:{}",localFolderPath,remoteFolderPath);
            // 上传文件
            uploadFolder(ftpClient, localFolderPath, remoteFolderPath);


            System.out.println("文件上传完成！");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 断开连接
                if (ftpClient.isConnected()) {
                    ftpClient.logout();
                    ftpClient.disconnect();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 上传文件夹中的所有 a.html 和 b.html 文件
     *
     * @param ftpClient       FTPClient 对象
     * @param localFolderPath 本地文件夹路径
     * @param remoteFolderPath 远程文件夹路径
     * @throws IOException 如果上传过程中发生错误
     */
    private static void uploadFolder(FTPClient ftpClient, String localFolderPath, String remoteFolderPath) throws IOException {
        File localFolder = new File(localFolderPath);
        if (!localFolder.exists() || !localFolder.isDirectory()) {
            throw new IOException("本地文件夹路径无效: " + localFolderPath);
        }

        // 遍历本地文件夹
        for (File file : localFolder.listFiles()) {
            if (file.isDirectory()) {
                // 如果是子文件夹，递归处理
                String subRemoteFolderPath = remoteFolderPath + "/" + file.getName();
                uploadFolder(ftpClient, file.getAbsolutePath(), subRemoteFolderPath);
            } else if (file.isFile()
                    && (file.getName().equals("question.html")
                    || (file.getName().equals("style.css")
                    && !(file.getAbsolutePath().contains("JoinGroupWord")) && !(file.getAbsolutePath().contains("MakeSentence")))
            )) {
                // 如果是目标文件，上传到 FTP 服务器
                log.info("filePath:{},remoteFolderPath:{}",file.getAbsolutePath(),remoteFolderPath);
                uploadFile(ftpClient, file, remoteFolderPath);
            }
        }
    }

    /**
     * 上传单个文件到 FTP 服务器
     *
     * @param ftpClient       FTPClient 对象
     * @param file            要上传的文件
     * @param remoteFolderPath 远程文件夹路径
     * @throws IOException 如果上传过程中发生错误
     */
    private static void uploadFile(FTPClient ftpClient, File file, String remoteFolderPath) throws IOException {
        // 确保远程文件夹存在
        if (!ftpClient.changeWorkingDirectory(remoteFolderPath)) {
            // 如果文件夹不存在，逐级创建
            String[] folders = remoteFolderPath.split("/");
            String path = "";
            for (String folder : folders) {
                if (!folder.isEmpty()) {
                    path += "/" + folder;
                    if (!ftpClient.changeWorkingDirectory(path)) {
                        if (ftpClient.makeDirectory(path)) {
                            ftpClient.changeWorkingDirectory(path);
                        } else {
                            throw new IOException("无法创建远程文件夹: " + path);
                        }
                    }
                }
            }
        }

        // 上传文件
        try (FileInputStream inputStream = new FileInputStream(file)) {
            boolean success = ftpClient.storeFile(file.getName(), inputStream);
            if (success) {
                System.out.println("文件上传成功: " + file.getAbsolutePath() + " -> " + remoteFolderPath + "/" + file.getName());
            } else {
                throw new IOException("文件上传失败: " + file.getAbsolutePath());
            }
        }
    }
}